package cn.edu.nju.askinginhand.util;

import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * JSON解析的类，负责将json字符串解析为相应的格式
 * 
 * @author ZhangZu
 * 
 */
public class JSONParser {
	// 根ip地址
	// private static String rootUrl = "http://10.0.2.2:8080/AskingHand/";
	public static String rootUrl = "http://192.168.1.106:8080/AskingHand/";

	public static String getRootURL() {
		return rootUrl;
	}

	/**
	 * 这里采用post请求方式，使用一个List保存请求参数，在外部写为： List <NameValuePair> params = new
	 * ArrayList <NameValuePair>(); params.add(new BasicNameValuePair("user",
	 * "123")); params.add(new BasicNameValuePair("pass", "3421"));
	 * 然后把这个List作为参数调用此方法
	 * 
	 * @param tailUrl
	 *            请求的url结尾，比如userAddAction?username=xx&password=xx
	 * @return
	 */
	public static String getOut(String tailUrl, List<NameValuePair> params) {
		String out = null;
		try {
			HttpClient client = new DefaultHttpClient();
			HttpPost httpRequest = new HttpPost(new URI(rootUrl + tailUrl));
			httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
			HttpResponse response = client.execute(httpRequest);
			System.out.println(response.getStatusLine());
			if (response.getStatusLine().getStatusCode() != 200) { // 200为成功
				System.out
						.println("response.getStatusLine().getStatusCode() != 200");
				return null;
			}

			HttpEntity entity = response.getEntity();
			if (entity != null) {
				System.out.println("entity!=null");
				out = EntityUtils.toString(entity);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return out;
	}

	/**
	 * 通过解析得到应该的root，此方法适用于root在第一层，不递归搜索
	 * 
	 * @param raw
	 *            原始的json字符串
	 * @param root
	 *            要获得的以root为根的字符串
	 * @return
	 */
	public static String removeRoot(String raw, String root) {
		String result = null;
		try {
			JSONObject jsonObject = new JSONObject(raw);// 解析
			result = jsonObject.get(root).toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 获取返回的string内容，格式为{"strResult":"xxx"}
	 * 
	 * @param jsonStr
	 * @return
	 */
	public static String getStringData(String jsonStr) {
		String result = null;
		try {
			JSONObject jsonObject = new JSONObject(jsonStr);
			result = jsonObject.get("strResult").toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 获取数组对象，数据以数组形式存储
	 * 如[{"id":1,"name":"teacher1","number":"t01","password":"t01"},
	 * {"id":2,"name":"teacher2","number":"t02","password":"t02"}]
	 * 
	 * @param jsonStr
	 *            服务器返回的json格式字符串
	 * @return
	 */
	public static List<Map<String, String>> getList(String jsonStr) {
		if(jsonStr ==null || jsonStr.equals(""))
			return new ArrayList<Map<String, String>>();
		
		List<Map<String, String>> list = null;
		JSONArray jsonArray;

		try {
			jsonArray = new JSONArray(jsonStr);

			list = new ArrayList<Map<String, String>>();

			for (int i = 0; i < jsonArray.length(); i++) {
				JSONObject jsonObject = jsonArray.getJSONObject(i);
				list.add(getMap(jsonObject.toString()));
			}
			return list;
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return list;
	}

	/**
	 * 获取单个对象，数据以map的形式存储
	 * 
	 * @param jsonStr
	 *            服务器返回的json格式字符串
	 * @return
	 */
	public static Map<String, String> getMap(String jsonStr) {
		JSONObject jsonObject = null;
		Map<String, String> valueMap = null;
		try {
			jsonObject = new JSONObject(jsonStr);
			Iterator<String> keyIter = jsonObject.keys();
			String key;
			String value;
			valueMap = new HashMap<String, String>();
			while (keyIter.hasNext()) {
				key = (String) keyIter.next();
				value = jsonObject.get(key).toString();
				if (value == null || value.equals("null"))
					value = "";
				valueMap.put(key,value);
			}
			return valueMap;
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return null;
	}
}
